﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using ECare.BUS.Data;
using ECare.BUS;
using ECare.Client.frms;

namespace ECare.Win.controls
{
    public partial class ucFormula : DevExpress.XtraEditors.XtraUserControl
    {
        public ucFormula()
        {
            InitializeComponent();

            this.Load += ucFormula_Load;
            //this.grd.CellDoubleClick += grd_CellDoubleClick;
            //   this.btnEdit.Click += btnEdit_Click;

            this.grd.CellDoubleClick += grd_CellDoubleClick;
        }

        void grd_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            //throw new NotImplementedException();
            if (e.RowIndex == -1)
                return;

            var entitye = this.grd.Rows[e.RowIndex].DataBoundItem as FormulaInfo;
            var frm = new frmFomulaInfo {entity = entitye};
            frm.Saved += frm_Saved;
            frm.ShowDialog();
        }

        public BindingList<FormulaInfo> source { get; set; }
        void ucFormula_Load(object sender, EventArgs e)
        {
            source = new BindingList<FormulaInfo>(FormulaHelper.GetFormulaInfos());
            this.grd.DataSource = source;

        }

        private void windowsUIButtonPanel1_ButtonClick(object sender, DevExpress.XtraBars.Docking2010.ButtonEventArgs e)
        {
            if (e.Button.Properties.Caption == "Edit")
            {
                if (this.grd.SelectedRows.Count == 0)
                    return;

                var entitye = this.grd.SelectedRows[0].DataBoundItem as FormulaInfo;
                var frm = new frmFomulaInfo();
                frm.entity = entitye;
                frm.Saved += frm_Saved;
                frm.ShowDialog();
            }
            else if (e.Button.Properties.Caption == "New")
            {
                var frm = new frmFomulaInfo();
                frm.entity = null;
                frm.Saved += frm_Saved;
                frm.ShowDialog();
            }
        }

        void frm_Saved(object entity)
        {
            if (source == null)
                source = new BindingList<FormulaInfo>();
            var role = entity as FormulaInfo;
            var findresult = source.FirstOrDefault(a => a.FormulaId == role.FormulaId);
            if (findresult == null)
                this.source.Add(role);
        }


    }
}
